<!--
 * @Author: your name
 * @Date: 2021-09-02 10:59:32
 * @LastEditTime: 2021-09-03 21:48:37
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /custom-post-card/src/views/finish.vue
-->
<template>
  <div class="container container_replace">
    <canvas v-show="resUrl === ''" id="postcard" class="canvas">
      你的浏览器版本过低，请更新...
    </canvas>
    <img
      v-show="resUrl !== ''"
      :src="resUrl"
      class="canvas"
      style="width: 375px; height: 449px"
    />
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { useRoute } from "vue-router";

let route = useRoute();
const resUrl = ref("");
//处理文本
const spiltText = (ctx, text, maxWidth) => {
  let textList = [];
  textList[0] = "致 最亲爱的老师:";
  let str = "         " + text;
  let currentRow = 1;
  let lineWidth = 0;
  let lastSubStrIndex = 0;
  for (let i = 0; i < str.length; i++) {
    lineWidth += ctx.measureText(str[i]).width;
    if (lineWidth > maxWidth) {
      textList[currentRow] = str.substring(lastSubStrIndex, i + 1);
      lineWidth = 0;
      lastSubStrIndex = i + 1;
      currentRow++;
    }
  }
  textList[currentRow] = str.substring(lastSubStrIndex, str.length);
  return textList;
};

//绘制明信片
const drawPostCard = () => {
  let canvas = document.getElementById("postcard");
  if (canvas.getContext) {
    //背景图
    let bg = new Image();
    bg.setAttribute("crossOrigin", "anonymous");
    //风景图
    let scenery = new Image();
    scenery.setAttribute("crossOrigin", "anonymous");
    //获取ctx上下文
    let ctx = canvas.getContext("2d");
    const width = 375;
    const height = 449;
    // 设置canvas的css宽高
    canvas.style.width = `${width}px`;
    canvas.style.height = `${height}px`;
    // 获取缩放比
    const ratio = window.devicePixelRatio || 1;
    // 设置canvas的宽高
    canvas.width = width * ratio;
    canvas.height = height * ratio;
    bg.src =
      "https://dgut-teacher-postcard-1255644734.file.myqcloud.com/images/postcard-bg.png";

    //加载背景图片
    bg.onload = () => {
      scenery.src = route.query.url;
      ctx.drawImage(bg, 0, 0, width * ratio, height * ratio);
      //加载文字
      let textList = spiltText(ctx, route.query.context, 300);
      ctx.font = "32px '楷体'";
      for (let i = 0; i < textList.length; i++) {
        ctx.fillText(textList[i], 20 * ratio, 275 * ratio + 70 * i);
      }
    };
    //加载风景图
    scenery.onload = () => {
      ctx.drawImage(scenery, 8 * ratio, 8 * ratio, 359 * ratio, 238 * ratio);
      resUrl.value = canvas.toDataURL();
    };
  }
};

onMounted(() => {
  drawPostCard();
});
</script>

<style scoped>
.container_replace {
  background-image: url("https://dgut-teacher-postcard-1255644734.file.myqcloud.com/images/completed-bg.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;
  justify-content: flex-start;
}
.canvas {
  margin-top: 20px;
  font-family: "楷体";
}


</style>
